package com.snail.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/15  16:24
 * @Description: TODO
 */
@Configuration
@EnableCaching
public class RedisConfiguration {
    //返回值是什么？Bean对象的类型，方法名是什么？Bean对象的名字
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        //对象中，使用redis连接工厂，才能利用yml的配置让我们的redisTemplate直接生效
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置序列化器，key不都是String
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //value的默认序列化方案，都直接使用json方案，可以传入网络，也可以存入redis中
        redisTemplate.setValueSerializer(RedisSerializer.json());
        //配置Hash类型的序列化方案
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }

    //Redis在Springboot中注解的配置方案，后面还需要使用redis的注解
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        //使用默认缓存配置
        //配置序列化方案
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return configuration;
    }
}
